package com.fl.nj.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 全局异常处理器
 * 统一捕获和处理控制器中的异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = Logger.getLogger(GlobalExceptionHandler.class.getName());

    /**
     * 处理所有未捕获的异常
     * 
     * @param request 请求对象
     * @param e       异常对象
     * @return 统一的错误响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ApiResponse<Object> handleException(HttpServletRequest request, Exception e) {
        logger.log(Level.SEVERE, "服务器内部错误: " + request.getRequestURI(), e);
        // 在生产环境中，可以根据不同的异常类型返回不同的错误消息
        // 这里为了安全，不向客户端暴露具体的错误堆栈信息
        return ApiResponse.internalError("服务器内部错误，请联系管理员");
    }

    /**
     * 处理数据库相关异常
     * 
     * @param request 请求对象
     * @param e       SQL异常对象
     * @return 统一的错误响应
     */
    @ExceptionHandler(SQLException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ApiResponse<Object> handleSQLException(HttpServletRequest request, SQLException e) {
        logger.log(Level.SEVERE, "数据库操作错误: " + request.getRequestURI(), e);
        return ApiResponse.internalError("数据库操作失败，请稍后重试");
    }

    /**
     * 处理资源未找到异常
     * 
     * @param request 请求对象
     * @param e       未找到元素异常
     * @return 统一的错误响应
     */
    @ExceptionHandler(NoSuchElementException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public ApiResponse<Object> handleNoSuchElementException(HttpServletRequest request, NoSuchElementException e) {
        logger.log(Level.WARNING, "资源未找到: " + request.getRequestURI(), e);
        return ApiResponse.notFound();
    }

    /**
     * 处理参数类型不匹配异常
     * 
     * @param request 请求对象
     * @param e       参数类型不匹配异常
     * @return 统一的错误响应
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ApiResponse<Object> handleMethodArgumentTypeMismatchException(HttpServletRequest request,
            MethodArgumentTypeMismatchException e) {
        logger.log(Level.WARNING, "参数类型错误: " + request.getRequestURI(), e);
        String paramName = e.getName();
        String requiredType = e.getRequiredType() != null ? e.getRequiredType().getSimpleName() : "正确类型";
        return ApiResponse.badRequest("参数 '" + paramName + "' 类型错误，请提供" + requiredType + "类型的值");
    }

    /**
     * 处理自定义业务异常
     * 
     * @param request 请求对象
     * @param e       业务异常对象
     * @return 统一的错误响应
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseEntity<ApiResponse<Object>> handleBusinessException(HttpServletRequest request,
            BusinessException e) {
        logger.log(Level.WARNING, "业务异常: " + request.getRequestURI(), e);
        // 根据业务异常中的状态码返回相应的HTTP状态
        HttpStatus status = e.getStatusCode() >= 400 && e.getStatusCode() < 600
                ? HttpStatus.valueOf(e.getStatusCode())
                : HttpStatus.INTERNAL_SERVER_ERROR;
        return new ResponseEntity<>(ApiResponse.error(e.getStatusCode(), e.getMessage()), status);
    }
}